/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable no-shadow */
/* eslint-disable react/jsx-no-bind */
import React, { useEffect, useState } from 'react';
import { message, Modal, Radio } from 'antd';
import StandardTable from '@/components/StandardTable';
import { getInnZoneList, zoneDispatch } from '@/services/area';

const Index = ({ title, visible, onOk, onCancel, getList, record, ...rest }) => {
  const { area_id: site_id, id } = record;

  const [tableData, setTableData] = useState([]);
  const [checkedId, setCheckedId] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const handleOk = () => {
    if (!tableData.map(val => val.site_id).includes(checkedId)) {
      message.warning('请选择需要分配的片区');
      return;
    }
    setSubmitting(true);
    zoneDispatch({ id, area_id: checkedId })
      .then(res => {
        const { code, msg } = res;
        if (code == 0) {
          message.success('分配成功');
          getList();
          onCancel();
        } else {
          message.error(msg);
        }
        setSubmitting(false);
      })
      .catch(() => {
        setSubmitting(false);
      });
  };

  const handleCancel = () => {
    onCancel();
  };

  const onRadioChange = (id, e) => {
    if (e.target.checked) {
      setCheckedId(id);
    } else {
      setCheckedId('');
    }
  };

  const columns = [
    {
      key: 'check',
      dataIndex: 'site_id',
      width: 60,
      render: site_id => (
        <Radio checked={checkedId == site_id} onChange={onRadioChange.bind(null, site_id)} />
      ),
    },
    {
      title: '片区',
      dataIndex: 'site_name',
    },
    {
      title: '负责人',
      dataIndex: 'site_charge',
    },
    {
      title: '手机号',
      dataIndex: 'site_phone',
    },
  ];

  useEffect(
    () => {
      if (visible) {
        setCheckedId(site_id);
        getInnZoneList().then(list => {
          setTableData(list);
        });
      }
    },
    [visible, site_id],
  );

  return (
    <Modal
      width={650}
      visible={visible}
      title={title}
      onOk={handleOk}
      onCancel={handleCancel}
      confirmLoading={submitting}
      {...rest}
    >
      <StandardTable
        rowKey="zone_id"
        columns={columns}
        data={{
          list: tableData,
        }}
        scroll={{ x: 600 }}
      />
    </Modal>
  );
};

export default Index;
